//
//  TestArray.swift
//  TestSwift
//
//  Created by 小星星吃KFC on 2021/5/29.
//

import Foundation


func TestArray(){
    //    let array = [1,4,2,5,3]
    let array = ["jim","tom","jack"]
    do{
        
        let arr = array.flatMap{ i in
            return [i]
        }
        print("flatMap加[]=\(arr)")
    }
    do{
        
        let arr = array.flatMap{ i in
            return i
        }
        print("flatMap不加[]=\(arr)")
    }
    
    do{
        
        let arr = array.compactMap { i in
            return "名字\(i)";
        }
        print("compactMap=\(arr)")
        
    }
    do{
        
        let arr = array.map { i in
            return "名字\(i)"
        }
        print("map=\(arr)")
        
    }
    // https://www.jianshu.com/p/07b59f4f0071
    do {
        /**
         map 最终将它们组成一个二维的数组；
         flatMap 中执行的 closure 返回的是同样的数组，但是 flatMap 将每一个返回的数组都拍扁，取出它的元素，构成一个大的一维数组。
         */
        let numbers = [[1, 2, 3, 4], [5, 6], [7]]
        
        let maped = numbers.map { $0 }
        let flatMapped = numbers.flatMap { $0 }
        
        print(maped)
        print(flatMapped)
        /// [[1, 2, 3, 4], [5, 6], [7]]
        /// [1, 2, 3, 4, 5, 6, 7]
    }
    
    
    do {
        
        let numbers = ["1", "2", "three", "///5///", "5"]
      
        do {
            
            let arr = numbers.map { number in
                return (Int(number))
            }
            print("numbers.map=\(arr)")
            
        }
        
        do {
            
            
            let arr = numbers.filter { (val) in
                return Int(val) != nil
            }
            print("numbers.filter=\(arr)")
            
        }
        
        do {
//            let arr = numbers.compactMap { (number) in
//                print(Int(number))
//                return Int(number)
//            }
//            print("compactMap=\(arr)")
            
            let arr =  numbers.compactMap { (val) in
//                print("compactMap=\(val)")
//                print(Int(val))
                return Int(val)
            }
            print("compactMap过滤返回为nil=\(arr)")
            
        }
        
//        numbers.map { (number) -> Int? in
//            print(Int(number))
//            //            return
//        }
        
        let mapResult = numbers.map { (number) -> Int? in
            return Int(number)
        }
        print(mapResult)
        // [Optional(1), Optional(2), nil, nil, Optional(5)]
        
        let compactMapResult = numbers.compactMap { (number) -> Int? in
            return Int(number)
        }
        print(compactMapResult)
        // [1, 2, 5]
        
        
    }
    
    
}
